const db = require('../utils/db');

module.exports = {
    /**
    * 获取未发来新消息的聊天对象id
    */
   async getOldSender(formData) {
       let sql = `
       SELECT DISTINCT sender FROM message_record 
       WHERE receiver = '${formData.user}' 
       and state = 0
       `;
       let result = await db.query(sql);
       return result;
   },
    /**
    * 获取发来新消息的聊天对象id
    */
   async getNewSender(formData) {
       let sql = `
       SELECT DISTINCT sender FROM message_record 
       WHERE receiver = '${formData.user}' 
       and state = 1
       `;
       let result = await db.query(sql);
       return result;
   },
    /**
     * 获取聊天室id
     */
    async getRoom(formData) {
        let sql = `
        SELECT * FROM chat_room 
        WHERE (user1_id = '${formData.user1}' 
        and user2_id = '${formData.user2}') 
        or (user2_id = '${formData.user1}' 
        and user1_id = '${formData.user2}') limit 1`;
        let result = await db.query(sql);
        if (Array.isArray(result) && result.length > 0) {
            result = result[0];
        } else {
            result = null;
        }
        return result;
    },
    /**
     * 添加聊天室id
     */
    async addRoom(formData) {
        let room_id = Date.now();
        let res = await db.insert('chat_room', {
            room_id: room_id,
            user1_id: formData.user1,
            user2_id: formData.user2
        });
        res = {room_id:room_id};
        return res;
    },
    /**
     * 添加聊天记录
     */
    async addMessage(formData) {
        let res = db.insert('message_record', formData);
        return res;
    },
    /**
     * 获取已读聊天记录
     */
    async getReadMessage(formData) {
        let sql = `
        SELECT sender, receiver, content, state, create_time FROM message_record
        WHERE room_id = '${formData.room}'
        and (state = 0 or sender = '${formData.user_id}')
       `;
        let res = await db.query(sql);
        return res;
    },
    /**
     * 获取未读聊天记录
     */
    async getUnreadMessage(formData) {
        let sql = `
        SELECT sender, receiver, content, state FROM message_record
        WHERE room_id = '${formData.room}'
        and state = 1 and receiver = '${formData.user_id}'
       `;
        let res = await db.query(sql);
        return res;
    },
    /**
     * 修改聊天记录状态
     */
    async modifyMessageStates(formData) {
        let sql = `
        UPDATE message_record set state=REPLACE(state,1,0)
        WHERE room_id = '${formData.room}'
        and receiver = '${formData.receiver}'
        `;
        let result = await db.query(sql);
        return result;
    }
}